417
class Solution {
    boolean[][] pacific;
    boolean[][] atlantic;
    int x = 0;
    int y = 0;

    public ListListInteger pacificAtlantic(int[][] heights) {
        ListListInteger ret = new ArrayList();
        x = heights.length;
        y = heights[0].length;
        pacific = new boolean[x][y];
        atlantic = new boolean[x][y];

        for (int i = 0; i  x; i++) {
            fun(heights, i, 0, true);
            fun(heights, i, y-1, false);
        }
        for (int i = 0; i  y; i++) {
            fun(heights, 0, i, true);
            fun(heights, x-1, i, false);
        }
        for (int i = 0; i  x; i++) {
            for (int j = 0; j  y; j++) {
                if (pacific[i][j] && atlantic[i][j]) {
                    ListInteger tmp = new ArrayList();
                    tmp.add(i);
                    tmp.add(j);
                    ret.add(tmp);
                }
            }
        }
        return ret;
    }

    public void fun(int[][] heights, int i, int j, boolean ocean) {
        boolean[][] tmp = null;
        if (ocean) {
            pacific[i][j] = true;
            tmp = pacific;
        } else {
            atlantic[i][j] = true;
            tmp = atlantic;
        } 
        int a = heights[i][j];
        i++;
        if (i  x && !tmp[i][j] && heights[i][j] = a) {
            fun(heights, i, j, ocean);
        }
        i -= 2;
        if (i = 0 && !tmp[i][j] && heights[i][j] = a) {
            fun(heights, i, j, ocean);
        }
        i++;
        j--;
        if (j = 0 && !tmp[i][j] && heights[i][j] = a) {
            fun(heights, i, j, ocean);
        }
        j += 2;
        if (j  y && !tmp[i][j] && heights[i][j] = a) {
            fun(heights, i, j, ocean);
        }
    }
}